








/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */








var nVehiculo = 60;

var motorGP = {
        reloj:[1],
        fecha:[1],
	mapHeight: 100010,
	mapWidth: 150010,
	nodeDistance: 1000,
	nodeRadius: 70,
	numNodesX:150,
	numNodesY:100,
	nodeArray:[],
	initNodeArray: function(){
		for(var i = 0; i< this.numNodesX;i++){
			for(var j=0; j< this.numNodesY;j++){
				this.nodeArray.push(new Node(this.nodeRadius+i*this.nodeDistance,
				this.nodeRadius+j*this.nodeDistance));
			}
		}
	},
	vehicleArray:[],
	initVehicleArray: function(){
		this.vehicleArray = [];
		for(var i=0; i < 60;i++){
			this.vehicleArray.push(new Vehicle(45000,30000,this.images[0],i));
		}
                /*console.log(this.vehicleArray);*/
	},
	images :[],
        pedidoArray:[],
	imgCount :0,
	imagesLoaded: false,
	loadImages : function(){
		var carImage = new Image();
		carImage.onload = function(){
			motorGP.images.push(this);
			motorGP.imgCount++;
			motorGP.imagesLoaded =true;
			if(motorGP.imagesLoaded){
				motorGP.initVehicleArray();
                                motorGP.timer = setInterval(updatePositions,400); 
				visualizer.draw();
			}
		};
		carImage.src = "resources/car.svg";
	}
        
};

function Rect(x,y,w,h){
	this.x=x;
	this.y=y;
	this.w=w;
	this.h=h;
}

function Canvas(canvas){
	this.canvas = canvas;
	this.ctx = canvas.getContext("2d");
	this.dirtyRects =[];
}

Canvas.prototype ={
	canvas: null,
	ctx:null,
	dirtyRects:[],
	clearCanvas : function(){
		var rect;
		while(this.dirtyRects.length !== 0){
			rect = this.dirtyRects.pop();
			this.ctx.clearRect(rect.x,rect.y,rect.w,rect.h);
		}
	}
};

function Node(x,y){
	this.x =x;
	this.y =y;
}

Node.prototype ={
	x:0,
	y:0,
	borderColor:'#606060',
	fillColor:'#AAAAAA',
	streetColor:'#DDDDDD',
	streetBorderColor:"#000000",
	radius:motorGP.nodeRadius,
	canvasX:0,
	canvasY:0,
	canvasRadius:0,
	canvasDistance:0,
	draw: function(visualizer){
		var ctx = motorGP.mapCanvas.ctx;
		this.canvasX = (this.x - visualizer.x) * visualizer.ratio;
		this.canvasY = (this.y - visualizer.y) * visualizer.ratio;
		this.canvasRadius = this.radius*visualizer.ratio;
		this.canvasDistance = motorGP.nodeDistance*visualizer.ratio;
		//dibujar las 2 calles
		ctx.fillStyle = this.streetColor;
		ctx.beginPath();
		ctx.rect(this.canvasX,this.canvasY - (this.canvasRadius /2),this.canvasDistance,this.canvasRadius);
		ctx.fill();
		motorGP.mapCanvas.dirtyRects.push(new Rect(this.canvasX-1,this.canvasY - (this.canvasRadius /2)-1,this.canvasDistance+2,this.canvasRadius+2));
		
		ctx.beginPath();
		ctx.rect(this.canvasX - (this.canvasRadius /2),this.canvasY,this.canvasRadius,this.canvasDistance);
		ctx.fill();
		motorGP.mapCanvas.dirtyRects.push(new Rect(this.canvasX - (this.canvasRadius /2)-1,this.canvasY-1,this.canvasRadius +2,this.canvasDistance+2));
		//dibujar el circulo
		ctx.beginPath();
		ctx.arc(this.canvasX,this.canvasY,this.canvasRadius,0,360,true);
		ctx.strokeStyle=this.borderColor;
		ctx.stroke();
		ctx.fillStyle = this.fillColor;
		ctx.fill();
		motorGP.mapCanvas.dirtyRects.push(new Rect(this.canvasX-this.canvasRadius -1,this.canvasY-this.canvasRadius -1,this.canvasRadius*2 +2,this.canvasRadius*2+2));
		
	}
};

function Vehicle(x,y,img,i){
	this.x=x;
	this.y=y;
	this.sprite = img;
        this.i = i;
}

function Pedido(x,y){
    this.x=x;
    this.y=y;
}

Pedido.prototype= {
    x:0,
    y:0,
    prioridad:10,
    side: 700,
    draw: function (visualizer){
        var ctx = motorGP.vehicleCanvas.ctx;
        var canvasX = (this.x - visualizer.x - this.side/2 + motorGP.nodeRadius/2) * visualizer.ratio;
	var canvasY = (this.y - visualizer.y) * visualizer.ratio;
        ctx.fillStyle = "#0000FF";
        ctx.beginPath();
	ctx.rect(canvasX,canvasY, this.side*visualizer.ratio,this.side*visualizer.ratio);
        ctx.fill();
    }
};

Vehicle.prototype ={
	x:0,
	y:0,
	width:motorGP.nodeRadius*4,
	heigth:motorGP.nodeRadius*4 *0.7,
	type: "auto",
	sprite: motorGP.images[0],
        routeColor: "#DDDDDD",
        coloresRuta: ["#44944A","#7B005B","#355E3B","#0000FF","#002FA7","#000080","#0047AB","#0131B4","#4B0082","#003153",
                      "#FF0000","#DC143C","#E34233","#800000","#00FF00","#4CBB17","#6B8E23","#50C878","#00A86B","#40826D",
                      "#6050DC","#FF00FF","#FD3F92","#C54B8C","#E0B0FF","#C8A2C8","#FEC3AC","#E6E6FA","#FFC0CB","#00FFFF",
                      "#30D5C8","#87CEFF","#9BC4E2","#7FFFD4","#FFFF00","#FDE910","#FFD700","#FFBF00","#E3A857","#FFBA00",
                      "#964B00","#94812B","#CC7722","#B87333","#DA8A5F","#800020","#8B00FF","#B57EDC","#9966CC","#660099",
                      "#66023C","#FF7028","#FF7F50","#FF8C69","#FBCEB1","#F5DEB3","#FFC8A0","#C0C0C0","#808080","#996600"],
	ruta : [],
	draw : function(visualizer){
		var ctx = motorGP.vehicleCanvas.ctx;
		var canvasX = (this.x - visualizer.x - this.width/2 + motorGP.nodeRadius/2) * visualizer.ratio;
		var canvasY = (this.y - visualizer.y) * visualizer.ratio;
		ctx.drawImage(this.sprite,canvasX-3,canvasY-3, this.width*visualizer.ratio+6,this.heigth*visualizer.ratio+6);
		this.drawRoutes(visualizer);
		motorGP.vehicleCanvas.dirtyRects.push(new Rect(canvasX-4,canvasY-4, this.width*visualizer.ratio+8,this.heigth*visualizer.ratio+8));
	},
	drawRoutes: function(visualizer){
                document.getElementById("fecha").innerHTML = "Fecha Simulada: "+motorGP.fecha[0];
                document.getElementById("hora").innerHTML = "Hora Simulada: "+motorGP.reloj[0];
                
		for(var i =0; i < this.ruta.length -1;i++){
			this.drawSegment(this.ruta[i],this.ruta[i+1],visualizer,this.coloresRuta[this.i]);
		}
	},
	drawSegment: function(n1,n2,v,color){
		var ctx = motorGP.vehicleCanvas.ctx;
		var canvasX = (n1.x - v.x) * v.ratio;
		var canvasY = (n1.y - v.y) * v.ratio;
		var canvasRadius = n1.radius*v.ratio;
		var canvasDistance = motorGP.nodeDistance*v.ratio;
		ctx.fillStyle = color;
		ctx.beginPath();
		var h,w;

		if(n2.x !== n1.x){
			canvasY -= canvasRadius /2;
			h = canvasRadius;
			var sign = n2.x < n1.x ? -1:1;
			w = canvasDistance * sign;
		}
		else{
			canvasX -= canvasRadius /2;
			w = canvasRadius;
			var sign = n2.y < n1.y ? -1:1;
			h = canvasDistance * sign;
		}
		ctx.rect(canvasX-1,canvasY-1,w+2,h+2);
		ctx.fill();                
	}
};

function Visualizer(x,y,w,h){
	this.x =x;
	this.y =y;
	this.w=w;
	this.h=h;

	this.nodeIsContained= function(node){
		var xConstraint = (node.x >= (this.x - node.radius) )&& 
		(node.x <= (this.x + this.w + node.radius) );
		var yConstraint = (node.y >= (this.y - node.radius) )&& 
		(node.y <= (this.y + this.h + node.radius) );
		return xConstraint || yConstraint; 
	};

	this.vehicleIsContained = function(v){
		var xConstraint = (v.x + v.width >=(this.x )) &&
		(v.x <= (this.x + this.w));
		var yConstraint = (v.y + v.height  >= (this.y) )&& 
		(v.y <= (this.y + this.h ) );
		return xConstraint || yConstraint; 
	};

	this.draw= function(){
		this.ratio = motorGP.mapCanvas.canvas.width/this.w;
		for(var i =0; i < motorGP.nodeArray.length;i++){
			var n = motorGP.nodeArray[i];
			if(this.nodeIsContained(n)){
				//n.draw(this);
			}
		}
		//motorGP.mapCanvas.dirtyRects.push(new Rect(0,0,motorGP.mapCanvas.canvas.width,motorGP.mapCanvas.canvas.height));
		motorGP.vehicleCanvas.dirtyRects.push(new Rect(0,0,motorGP.vehicleCanvas.canvas.width,motorGP.vehicleCanvas.canvas.height));
		for(var i=0; i < nVehiculo;i++){
			var v = motorGP.vehicleArray[i];
			if(this.vehicleIsContained(v)){
				v.draw(this);
			}
		}
	};
        this.drawUpdates= function(){
		//motorGP.mapCanvas.dirtyRects.push(new Rect(0,0,motorGP.mapCanvas.canvas.width,motorGP.mapCanvas.canvas.height));
		motorGP.vehicleCanvas.dirtyRects.push(new Rect(0,0,motorGP.vehicleCanvas.canvas.width,motorGP.vehicleCanvas.canvas.height));
		for(var i=0; i < nVehiculo;i++){
			var v = motorGP.vehicleArray[i];
			if(this.vehicleIsContained(v)){
				v.draw(this);
			}
		}
                for(var i=0; i < motorGP.pedidoArray.length;i++){
                    var ped = motorGP.pedidoArray[i];
                    ped.draw(this);
                }
	};
}


function procesandoData(stringJson) {
    var myobject = JSON.parse(stringJson);
    for (var i = 0; i < myobject.vehiculos.length; i++) {
        motorGP.vehicleArray[i].x = myobject.vehiculos[i].x*motorGP.nodeDistance; // el vehiculo i del arreglo de vehiculos
        motorGP.vehicleArray[i].y = myobject.vehiculos[i].y*motorGP.nodeDistance;
        //alert(motorGP.vehicleArray[0].x);
        //crea lista de rutas
        motorGP.vehicleArray[i].ruta =[];
        for (var j = 0; j < myobject.vehiculos[i].ruta.length; j++) {
            node = motorGP.nodeArray[myobject.vehiculos[i].ruta[j].y + motorGP.numNodesY * myobject.vehiculos[i].ruta[j].x];   // obtener el nodo                           
            motorGP.vehicleArray[i].ruta.push(node);   //ingresar el nodo     
            
        }

    }
    motorGP.pedidoArray =[];
    for(var i=0;i< myobject.pedidos.length;i++){
        orden = new Pedido(myobject.pedidos[i].x*motorGP.nodeDistance,myobject.pedidos[i].y*motorGP.nodeDistance);
        motorGP.pedidoArray.push(orden);
    }
    motorGP.reloj = [];
    motorGP.fecha = [];
    //motorGP.reloj[0] = "00:00";
    motorGP.fecha[0] = myobject.fecha;
    motorGP.reloj[0] = myobject.reloj;
}

var xmlhttp;
var idCarro="";
var idPedido="";
var idCliente="";
        
function loadXMLDoc(url,funcion){
	if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else{// code for IE6, IE5
	  	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	url="actualizaPosRutaPron.htm";
        url+="?idCarro=";
        if (idCarro!=="") {
            url+= idCarro;
        } else {
            url+="";
        }
        url+="&idPedido=";
        if (idPedido!=="") {
            url+= idPedido;
        }else {
            url+="";
        }
        url+="&idCliente=";
        if (idCliente!=="") {
            url+= idCliente;
        }else {
            url+="";
        }


	xmlhttp.onreadystatechange=funcion;
	//alert('aca1');
	xmlhttp.open("GET",url,true);
	//alert('aca2');
	xmlhttp.send();
}


function llamaActualizaPos(){
    loadXMLDoc("ruta.jsp",function(){
      	//alert('aca3');
      	if (xmlhttp.readyState===4 && xmlhttp.status===200){
                    //alert('aca4');
                    var responseText =xmlhttp.responseText;
                    //myJSONObject = eval('(' + responseTxt + ')');
                    //funcionLlena(responseTxt);
                    procesandoData(responseText);
      	}
    });
}

function updatePositions(){
	llamaActualizaPos();
	motorGP.vehicleCanvas.clearCanvas();
	motorGP.vehicleCanvas.clearCanvas();
	visualizer.drawUpdates();
}

